package com.my.easymall.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther Summerday
 *
 * 全站乱码处理
 */
//@WebFilter("/EncodingFilter")
public class EncodingFilter implements Filter {

    private String targetEncode = null;//默认utf-8
    private boolean user_encode = false;//默认关闭iso8859-1处理

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //全局响应乱码解决
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        request.setCharacterEncoding(targetEncode);
        response.setContentType("text/html;charset="+targetEncode);

        MyHttpServletRequest myReq = new MyHttpServletRequest(request,targetEncode);
        request = user_encode?myReq:request;
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {
        //获取web.xml配置的初始化参数
        targetEncode = config.getServletContext().getInitParameter("targetEncode");
        user_encode = Boolean.parseBoolean(config.getServletContext().getInitParameter("use-encode"));
    }

    public void destroy() {
    }

}



